import { Button, Cascader, CascaderProps, DatePicker, Drawer, Form, Input, Select, TreeSelect, message } from 'antd';
import dayjs from 'dayjs';
import moment from 'moment';
import { useEffect, useState } from 'react';
import "../indexRoom.less"
import { useDetermineCardType } from '@/hooks/DetermineCardType';
import { useDeleteConfirm } from '@/hooks/useAlartMolder';
// import IsSuiteRetrunCard from "./IsSuiteRetrunCard"
// import ChangeOrdinary from './ChangeOrdinary'; 
import { getLocale, useIntl } from '@umijs/max';
interface Prpos {
  showDrawerFormflag: boolean;
  dataRoomMsg: any;
  setshowDrawerFormflag: (Event: boolean) => void;
  RoomAllList: RoomList[];
  list2: RoomList[];
  setsendMsg: (event: stateObj) => void
  setType: (event: string) => void
  setChangeRoomsMsg: (event: CardMSg) => void
  setIsChangeRooms: (Event: number) => void;
  setNumId: (Event: number) => void;
  setGetcardMsg: any
}
interface Option {
  value: string;
  label: string;
  children?: Option[];
}
const showDrawerForm: React.FC<Prpos> = ({
  RoomAllList, showDrawerFormflag, dataRoomMsg, list2, setGetcardMsg,
  setNumId, setshowDrawerFormflag,
  setsendMsg, setType, setChangeRoomsMsg
}) => {
  const intl = useIntl()
  // 管理卡true 客人卡false
  const [CardType, setCardType] = useState(false)
  // 管理卡类型
  const [ManageCardType, setManageCardType] = useState<string | boolean>("")
  // 判断管理卡是否带楼层
  const [Isfoorflag, setIsfoorflag] = useState(false)
  // 树形下拉选择
  const [treeData, settreeData] = useState<{ value: number; label: string; }[]>([]);
  // 弹窗表头
  const [CardTitle, setCardTitle] = useState<string | boolean>("")
  const newOptions: { value: number; label: string; }[] = [];
  // 点击换房状态
  const [ChangeRoom, setChangeRoom] = useState(false)
  // 点击续住的状态
  const [ExtendedStay, setExtendedStay] = useState(false)
  // 续住和换房只能存在一个
  const shouldShowButton = ChangeRoom || ExtendedStay;
  // 换房的值
  const [value, setValue] = useState<string>("");
  // 判断是否套房
  const [IsSuite, setIsSuite] = useState(false)
  // 离店天数 
  const [ReturnDay, setReturnDay] = useState(1)
  const [form] = Form.useForm();
  // 是否挂失卡
  const [IsLostCard, setIsLostCard] = useState(false)
  // 获取房卡到期小时时间
  const [returnRoomTimer, setreturnRoomTimer] = useState(14)
  const { TextArea } = Input;
  // 续住下拉选择 下面处理了默认1天时间的赋值 
  const [Option1, setOption1] = useState([{
    value: 1,
    label: "1天"
  }])
  // 弹出框传入的值 
  const [ModeMsg, setModeMsg] = useState({
    current: null, // 当前房间数据
    target: null // 换房目标房间数据
  })
  // 监听换卡上报的信息更新form数据
  useEffect(() => {
    if (dataRoomMsg) {
      func()
    }
  }, [dataRoomMsg, CardType])



  useEffect(() => {
    for (let a = 2; a <= 60; a++) {
      newOptions.push({ value: a, label: `${a}天` });
    }
    setOption1([...Option1, ...newOptions])
  }, [])

  // 监听卡片切换时显示不同卡类型的数据 调用此函数
  const func = () => {
    if (dataRoomMsg.data.hasOwnProperty("cardType")) {
      // 判断是否管理卡
      setCardType(true)
      // 获取管理卡类型
      let [str] = useDetermineCardType("", "", dataRoomMsg.data.cardType)
      setManageCardType(str)
      // 设置表单表头
      setCardTitle(str)
      // 判断是否关联楼层
      dataRoomMsg.data.floor ? setIsfoorflag(true) : setIsfoorflag(false)
      // 表单赋值
      form.setFieldValue("realName", dataRoomMsg.data.cardHolder)
      form.setFieldValue("mobile", dataRoomMsg.data.buildingName)
      form.setFieldValue("CheckOutTimer", dataRoomMsg.data.expirationDate)
      form.setFieldValue("checkin", dataRoomMsg.data.issuingTime)
    } else if (dataRoomMsg.data.hasOwnProperty("loassCardType")) { // 判断挂失卡    
      setIsLostCard(true)
      let [str] = useDetermineCardType("", "", dataRoomMsg.data.loassCardType)
      setCardTitle("挂失卡")
      // 需要异步更新表单
      setTimeout(() => {
        form.setFieldValue("realName", dataRoomMsg.data.cardHolder)
        form.setFieldValue("mobile", str)
        form.setFieldValue("CheckOutTimer", dataRoomMsg.data.expirationDate)
        form.setFieldValue("checkin", dataRoomMsg.data.issuingTime)
      }, 100)

    } else {
      // 判断换卡成客人卡之后把管理卡状态关闭
      setCardType(false)
      setIsfoorflag(false)
      // 处理 TreeSelect 组件能处理的数据
      let arr: any = []
      let arr1: any = []
      for (var a in RoomAllList) {
        // arr.push({
        //   title: "第" + RoomAllList[a].layer + "层",
        //   value: RoomAllList[a].layer,
        //   children: RoomAllList[a].list.map((item: any) => {
        //     if (item.childRooms) {
        //       return {
        //         title: item.roomName,
        //         value: item.roomName,
        //         children: item.childRooms.map((l: { roomName: string; }) => {
        //           return {
        //             value: l.roomName,
        //             title: l.roomName
        //           }
        //         }) 
        //       }
        //     } else {
        //       return {
        //         value: item.roomName,
        //         title: item.roomName
        //       }
        //     }
        //   })
        // })
        arr1.push({
          label: "第" + RoomAllList[a].layer + "层",
          value: RoomAllList[a].layer,
          children: RoomAllList[a].list.map((item: any) => {
            if (item.childRooms) {
              return {
                label: item.roomName,
                value: item.roomName,
                children: item.childRooms.map((l: { roomName: string; }) => {
                  return {
                    value: l.roomName,
                    label: l.roomName
                  }
                })
              }
            } else {
              return {
                value: item.roomName,
                label: item.roomName
              }
            }
          })
        })
        settreeData(arr)
        setoptions(arr1)
      }
      // 获取当前卡退房的小时
      RetrunHours()
      // 套房
      setCardTitle(dataRoomMsg.data.bName + "-" + dataRoomMsg.data.roomTypeName)
    }
    Updatafrom()
    // 处理下拉选择续住天数
    const startOfDay = dayjs().startOf('day');

    // 设置传入的日期和时间（2024-05-05 14:00:00）
    const targetDateTime = dayjs(dataRoomMsg.data.checkout);

    // 计算两个日期之间的天数差异
    const daysDifference = targetDateTime.diff(startOfDay, 'day');

    setReturnDay(daysDifference)
  }
  // 计算退房小时数
  const RetrunHours = () => {
    const date = new Date(dataRoomMsg.data.checkout);
    const hours = date.getHours();
    const hoursStr = hours.toString().padStart(2, '0');
    setreturnRoomTimer(parseInt(hoursStr))
  }
  // from表单赋值
  const Updatafrom = () => {
    // 判断是否套房 写两次是 因为管理卡切换房卡会报错 必须写两次
    if (dataRoomMsg.data.subRoomNo) {
      setIsSuite(true)
      form.setFieldValue("roomName", dataRoomMsg.data.roomNo + " _ " + dataRoomMsg.data.subRoomNo)
    } else {
      setIsSuite(false)
      if (!CardType) {
        form.setFieldValue("roomName", dataRoomMsg.data.roomName)
      }
    }
    // 管理卡和客人卡同用一个表单 状态控制显示
    if (!CardType) {
      form.setFieldValue("mobile", dataRoomMsg.data.mobile)
      form.setFieldValue("CheckOutTimer", dataRoomMsg.data.checkout)
      form.setFieldValue("checkin", dataRoomMsg.data.checkin)
      form.setFieldValue("realName", dataRoomMsg.data.realName)
    }
    form.setFieldValue("floor", dataRoomMsg.data.floor)
    form.setFieldValue("cardNum", dataRoomMsg.data.cardNum)
  }

  // 更换房间
  const onChange = (newValue: string) => {
    setValue(newValue);
  };
  // 切换天数给时间选择器赋值
  const handleChangeDay2 = (value: string) => {
    const startOfDay = dayjs().startOf('day');
    // 在当前日期的零点基础上增加天数
    const daysAdded = startOfDay.add(parseInt(value), 'day');
    // 在增加天数后的基础上设置小时数
    const finalTime = daysAdded.hour(parseInt(returnRoomTimer.toString(), 10)).minute(0).second(0);
    form.setFieldValue("checkout", moment(finalTime.format('YYYY-MM-DD HH:mm:ss')))
  }

  // 点击时间选择器给下拉框赋值
  const checkoutTImer = (value: any) => {
    const specificTime = dayjs(value.$d);
    const currentTime = dayjs().hour(parseInt(returnRoomTimer.toString(), 10));
    const differenceInDays = specificTime.diff(currentTime, 'day');
    differenceInDays < 0 ? Math.abs(differenceInDays) : differenceInDays
    form.setFieldValue("renewal", differenceInDays + 1)
  }
  // 续住默认向后延一天
  const defaultHourValue = dayjs().add(1, "day").set('hour', returnRoomTimer).startOf('hour').format('YYYY-MM-DD HH:mm:ss');
  function extractNumberBeforeDash(str: string) {
    // 检查字符串中是否包含 '-'
    if (str.includes('-')) {
      // 使用正则表达式匹配 - 符号前面的所有数字
      var match = str.match(/^(\d+)-/);
      // 如果匹配成功，返回 true 和匹配到的数字
      if (match) {
        return { found: true, number: match[1] };
      }
    }
    // 如果没有找到 '-' 或者没有匹配到数字，返回 false 和 null
    return { found: false, number: null };
  }
  // 发卡
  const Issuing = (): any => {
    // 获取发卡JSON 
    let data = JSON.parse(dataRoomMsg.data.cmdInfo)
    // 换房发卡
    if (ChangeRoom) {
      if (value.length <= 1) return message.error("请选择正确的房间")
      let { found, number } = extractNumberBeforeDash(value)
      // return
      // 换房目标是套房
      if (found) {
        let GetRoomId: RoomList = list2.find((item) => item.roomName == number)
        if (!dataRoomMsg.data.subRoomNo) return message.error("不同房型不可换房")
        if (GetRoomId.status == '3') {
          useDeleteConfirm(`${GetRoomId.roomName}已入住，是否继续发卡`, "", (val) => {
            if (val) {
              setNumId(1)
              let { id, ...result } = data
              if (GetRoomId.childRooms) {
                let res = GetRoomId.childRooms.find((item: { roomName: string; }) => item.roomName == value)
                let SendData = { ...result, roomid: res.roomId }
                setType("套房换房")
                setsendMsg(SendData)
                setGetcardMsg({
                  ...dataRoomMsg.data, subRoomNo: value,
                  roomName: res.roomName, roomNo: GetRoomId.roomNo, roomId: GetRoomId.roomId, cmdInfo: JSON.stringify(SendData)
                })
              } else {
                message.error("不同房型不可换房")
              }
            }
          })
        } else {
          let { id, ...result } = data
          // 套房
          if (GetRoomId.childRooms) {
            let res = GetRoomId.childRooms.find((item: { roomName: string; }) => item.roomName == value)
            let SendData = { ...result, roomid: res.roomId }
            setType("套房换房")
            setsendMsg(SendData)
            setGetcardMsg({
              ...dataRoomMsg.data, subRoomNo: value,
              roomName: res.roomName, roomNo: GetRoomId.roomNo, roomId: GetRoomId.roomId, cmdInfo: JSON.stringify(SendData)
            })
          }
        }

      } else {
        // 换房目标房普通房间
        let GetRoomId: any = list2.find((item) => item.roomName == value)
        console.log(dataRoomMsg.data)
        if (dataRoomMsg.data.subRoomNo) return message.error("不同房型不可换房")
        // return 
        if (GetRoomId.status == '3') {
          useDeleteConfirm(`${GetRoomId.roomName}已入住，是否继续发卡`, "", (val) => {
            if (val) {
              setNumId(1)
              let { roomid, ...res } = data
              setsendMsg({ ...res, roomid: GetRoomId.roomId })
              setType("套房换房")
              // 更换原始数据中替换成目标房间的数据
              let ChangeInRoom = {
                ...dataRoomMsg.data,
                cmdInfo: JSON.stringify({ ...res, roomTypeName: GetRoomId.roomTypeName, id: GetRoomId.id, roomid: GetRoomId.roomId }),
                roomId: GetRoomId.roomId, roomName: value, roomNo: GetRoomId.roomNo
              }
              setGetcardMsg(ChangeInRoom)
            }
          })

        } else {

          let { roomid, ...res } = data
          setsendMsg({ ...res, roomid: GetRoomId.roomId })
          setType("套房换房")
          // 更换原始数据中替换成目标房间的数据
          let ChangeInRoom = {
            ...dataRoomMsg.data,
            cmdInfo: JSON.stringify({ ...res, roomTypeName: GetRoomId.roomTypeName, id: GetRoomId.id, roomid: GetRoomId.roomId }),
            roomId: GetRoomId.roomId, roomName: value, roomNo: GetRoomId.roomNo
          }
          setGetcardMsg(ChangeInRoom)
        }

      }

    } else {
      // 续住发卡
      let AA = form.getFieldValue("checkout")
      let Timer = dayjs(AA.$d).format('YYYY-MM-DD HH:mm:ss')
      let res = { ...dataRoomMsg.data, checkout: Timer }
      let Senddata = { ...data, endtime: Timer }
      setsendMsg(Senddata)
      setType("续住")
      setChangeRoomsMsg(res)
    }
  }

  // 退卡     
  const RetrunRoom = () => {
    let data = { "cardclass": "clearcard", "lockclass": "1", "shanqu": "1", "pass": "FFFFFFFFFFFF", "uuid": "autoread111" };
    setsendMsg(data)
    setType("上报退卡")
    setChangeRoomsMsg(dataRoomMsg.data)
  }

  const onClose = () => {
    setshowDrawerFormflag(false)
  }
  const titleDiv = (
    <>
      <div style={{ fontSize: "20px" }}>{CardTitle}</div>
    </>
  )


  const [options, setoptions] = useState()

  const onChangeTree: CascaderProps<Option>['onChange'] = (value: any) => {
    setValue(value ? value[value.length - 1] : '')
  };
  return (
    <>
      {/* {
        ChangeOrdinaryflag && <ChangeOrdinary
          ChangeOrdinaryflag={ChangeOrdinaryflag}
          ModeMsg={ModeMsg}
          setIsChangeRooms={setIsChangeRooms}
          setChangeOrdinaryflag={setChangeOrdinaryflag}
          setsendMsg={setsendMsg}
          setType={setType}
        />
      }

      {
        isModalOpen && <IsSuiteRetrunCard
          isModalOpen={isModalOpen}
          setIsModalOpen={setIsModalOpen}
          ModeMsg={ModeMsg}
          setIsChangeRooms={setIsChangeRooms}
        />
      } */}
      <Drawer
        title={titleDiv}
        open={showDrawerFormflag}
        onClose={onClose}
        mask={false}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item label={ManageCardType ? intl.formatMessage({ id: "business.Cardholder" }) : IsLostCard ? intl.formatMessage({ id: "business.Cardholder" }) : intl.formatMessage({ id: "business.Occupants" })} name="realName" >
            <Input style={{ color: "#1677FF", fontWeight: "700" }} disabled />
          </Form.Item>
          {
            dataRoomMsg.data.buildingName == "" ? <></> : <Form.Item
              label={ManageCardType ? intl.formatMessage({ id: "business.Manage building" }) : IsLostCard ? intl.formatMessage({ id: "business.Loss type" }) : intl.formatMessage({ id: "business.Mobile" })}
              name="mobile"
            >
              <Input style={{ color: "#1677FF", fontWeight: "700" }} disabled />
            </Form.Item>
          }
          {
            // 根据Isfoorflag的值决定是否渲染表单项
            Isfoorflag ? (
              <Form.Item
                label={intl.formatMessage({ id: "Manage floors" })}
                name="floor"
              > <TextArea style={{ color: "#1677FF", fontWeight: "700" }} value={dataRoomMsg.data.floor} disabled rows={3} maxLength={6} /></Form.Item>
            ) : (
              <></>
            )
          }
          {
            !CardType && !IsLostCard && <Form.Item
              label={IsSuite ? intl.formatMessage({ id: 'business.suite' }) : intl.formatMessage({ id: "business.Room" })}
              name="roomName"
              rules={[{ required: ChangeRoom, message: intl.formatMessage({id:"business.Please select a different room"}) }]}
            >
              {!ChangeRoom ? (
                <Input style={{ color: "#1677FF", fontWeight: "700" }} disabled />
              ) : (
                // <TreeSelect
                //   showSearch
                //   style={{ width: '100%' }}
                //   dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                //   placeholder="请选择更换的房间"
                //   allowClear
                //   value={value}
                //   onChange={onChange}
                //   treeData={treeData}
                // />
                <Cascader options={options} onChange={onChangeTree} style={{ width: '100%' }} />
              )}
            </Form.Item>
          }
          <Form.Item
            label={intl.formatMessage({id:"business.Room card"})}
            name="cardNum"

          >
            <Input style={{ color: "#1677FF", fontWeight: "700" }} disabled />
          </Form.Item>
          <Form.Item
            label={CardType ? intl.formatMessage({id:"business.Card issuance time"}) : IsLostCard ? intl.formatMessage({id:"business.Card issuance time"}) : intl.formatMessage({id:"business.Check-in time"})}
            name="checkin"
          >
            <Input style={{ color: "#1677FF", fontWeight: "700" }} disabled />
          </Form.Item>

          {
            ExtendedStay ?
              <Form.Item
                label={intl.formatMessage({id:"business.Check-out time"})}
                name="checkout"
                initialValue={moment(defaultHourValue)}
              >
                <DatePicker onChange={checkoutTImer} showTime format="YYYY-MM-DD HH:mm:ss" />
              </Form.Item> :
              <Form.Item
                label={CardType ? intl.formatMessage({id:"business.expiration date"}) : IsLostCard ? intl.formatMessage({id:"business.expiration date"}) : intl.formatMessage({id:"business.Check-out time"})}
                name="CheckOutTimer"
                initialValue={dataRoomMsg.data.checkout}
              >
                <Input style={{ color: "#1677FF", fontWeight: "700" }} disabled />
              </Form.Item>
          }
          {
            ExtendedStay && !IsLostCard && <Form.Item label={intl.formatMessage({id:"business.Keep staying Days"})} name='renewal' initialValue={ReturnDay}>
              <Select
                options={Option1}
                onChange={handleChangeDay2}
              />
            </Form.Item>
          }
          {/* 管理卡和挂失卡 不显示操作 */}
          {!CardType && !IsLostCard &&
            <Form.Item>
              {shouldShowButton && <Button type="primary" onClick={Issuing}>{intl.formatMessage({id:"business.Issuing"})}</Button>}&emsp;
              {!ChangeRoom && <Button type="primary" danger={ExtendedStay} onClick={() => {
                setExtendedStay(!ExtendedStay)
                form.setFieldValue("CheckOutTimer", dataRoomMsg.data.checkout)
                form.setFieldValue("renewal", ReturnDay)
                form.setFieldValue("checkout", moment(dayjs().add(1, "day").set('hour', returnRoomTimer).startOf('hour').format('YYYY-MM-DD HH:mm:ss')))
              }}> {ExtendedStay ? "取消续住" : "续住"} </Button>} &emsp;
              {!ExtendedStay && !ChangeRoom && <Button type="primary" danger onClick={RetrunRoom}>退房</Button>}&emsp;
              {!ExtendedStay && <Button type="primary" danger={ChangeRoom} onClick={() => {
                setChangeRoom(!ChangeRoom)
                if (ChangeRoom) {
                  if (dataRoomMsg.data.subRoomNo) {
                    setIsSuite(true)
                    form.setFieldValue("roomName", dataRoomMsg.data.roomNo + " _ " + dataRoomMsg.data.subRoomNo)
                  } else {
                    form.setFieldValue("roomName", dataRoomMsg.data.roomName)
                  }
                }

              }}> {ChangeRoom ? "取消换房" : "换房"} </Button>}&emsp;
            </Form.Item>
          }
        </Form>
      </Drawer>
    </>
  );
};

export default showDrawerForm